import fs from "fs-extra";
import path from "path";
import { CmdOption } from "../CmdOption.js";
import { toolchain, IBuildInfo } from "../toolchain.js";
import { Hudson } from "./hudson.js";
import { env } from "../env.js";
import { sendRobotMsg, setDefaultChatId } from "./alert.js";

export async function saveBuildHistory(): Promise<void> {
    const historyInfoFile = path.join(env.envRoot, 'history.json');
    let book: Record<string, CmdOption>;
    if (fs.existsSync(historyInfoFile)) {
        book = await fs.readJSON(historyInfoFile);
    } else {
        await fs.ensureFile(historyInfoFile);
        book = {};
    }
    const jn = Hudson.getJobName();
    const bn = Hudson.getBuildNumber();
    book[`${jn}#${bn}`] = toolchain.option;
    await fs.writeJSON(historyInfoFile, book, { spaces: 2 });
}

export async function handleRemote(rebuild: string): Promise<{ code: number, option?: CmdOption }> {
    // 解析remote参数，格式为: from:aaa;buildNum:xxx;chatId:yy;msgId:zzz
    const args: Record<string, string> = {};
    const pairs = rebuild.split(';');
    for (const pair of pairs) {
        const kvs = pair.split(':');
        if (kvs.length == 2) {
            args[kvs[0]] = kvs[1];
        }
    }
    const from = args['from'];
    const buildNum = args['buildNum'];
    const chatId = args['chatId'];
    const msgId = args['msgId'];

    if (chatId) {
        setDefaultChatId(chatId);
    }

    console.log(`remote parameters: from=${from}; buildNum=${buildNum}; chatId=${chatId}; msgId=${msgId}`);

    if (from == 'rebuild') {
        // 重新构建，读取指定的历史构建信息，覆盖当前的构建参数
        const historyInfoFile = path.join(env.envRoot, 'history.json');
        if (fs.existsSync(historyInfoFile)) {
            const book: Record<string, CmdOption> = await fs.readJSON(historyInfoFile);
            const jobName = Hudson.getJobName();
            const option = book[`${jobName}#${buildNum}`];
            if (option) {
                console.log('read history sucessfully:', rebuild);
                return { code: 0, option };
            }
            console.error('cannot find history build info for:', rebuild, jobName, buildNum, chatId);
        }   
    }

    if (from == 'cmd') {
        // 飞书消息命令构建，直接发送开始构建的回复
        const jobName = Hudson.getJobName();
        const bn = Hudson.getBuildNumber();
        const logLink = Hudson.getLogUrl();
        await sendRobotMsg('text', `${jobName} #${bn} 开始构建...，[点击查看日志](${logLink})`, undefined, chatId, msgId);
        return { code: 0 };
    }

    return { code: -1 };    
}

export async function saveBuildInfo(): Promise<void> {
    const buildInfoFile = path.join(toolchain.params.workSpacePath, '../.build/buildInfo.json');
    let book: Record<string, IBuildInfo>;
    if (fs.existsSync(buildInfoFile)) {
        book = await fs.readJSON(buildInfoFile);
    } else {
        await fs.ensureFile(buildInfoFile);
        book = {};
    }
    const fbv = await toolchain.unity.getFullBuildVer();
    book[fbv] = toolchain.buildInfo;
    await fs.writeJSON(buildInfoFile, book, { spaces: 2 });
}
